import { HTTP_CONFIG } from '../config'
import md5 from './md5.min'

const ERR_CODE = 200
let errMsgWhiteList = [
  '请先申请企业认证',
  'Result must not be null!',
  '未找到该简历'
]
// api doc http://xianmai.aishangyangyu.com:7070/api/apidoc/index.html

// sign的生成
const sign = (params, secret) => {
  if (secret === undefined) {
    secret = 'D98TZQWpTVlb1nqfkfO615U5ZEignoqW'
  }
  let result = secret
  let sortedParams = Object.keys(params).sort()
  for (let i = 0; i < sortedParams.length; i++) {
    let k = sortedParams[i]
    result += k + params[k]
  }
  result += secret
  return md5(result)
}

class HTTP {
  createURL(url, param) {
    // POST URL 参数拼接
    if (Object.keys(param).length) {
      param.sign = sign(param)
    }
    var urlLink = ''
    for (let item in param) {
      var link = '&' + item + '=' + param[item]
      urlLink += link
    }
    urlLink = url + '?' + urlLink.substr(1)
    return urlLink.replace(' ', '')
  }

  request(params) {
    let data = params.data || {}
    let urlData = params.urlData || {}
    if (params.method !== 'POST') {
      data.sign = sign(data)
    } else {
      params.url = this.createURL(params.url, urlData)
    }
    let url = HTTP_CONFIG.baseUrl + params.url
    if (params.oldURL) {
      url = HTTP_CONFIG.oldUrl + params.url
    }
    if (params.newURL) {
      url = HTTP_CONFIG.newUrl + params.url
    }

    wx.request({
      url,
      method: params.method || 'GET',
      header: {
        Authorization: wx.getStorageSync('userToken') || ''
      }, 
      data: data,
      success: (res) => {
        let code = res.statusCode.toString()
        if (code.startsWith('2')) {
          if (res.data.code == ERR_CODE || res.data.ErrCode == 0) {
            params.success && params.success(res.data.data || res.data.Response)
          } else {
            params.fail && params.fail(res.data)
            try {
              if (res.data.message == '请重新登录！') {
                // 偶尔出现token自动被清除时要求重新登录
                clearStorage()
                wx.navigateTo({
                  url: `/pages/login/login`
                })
              }
            } catch (e) {}
            wx.showToast({
              title: res.data.message,
              icon: 'none'
            })
          }
        } else {
          this.httpError()
        }
      },
      fail: (err) => {
        this.httpError()
      }
    })
  }

  httpError(errCode) {
    wx.showToast({
      title: '网络错误，请稍后再试～',
      icon: 'none',
      duration: 2000
    })
  }
}

function clearStorage() {
  wx.removeStorageSync('address')
  wx.removeStorageSync('shareCode')
  wx.removeStorageSync('userToken')
  wx.removeStorageSync('userInfo')
  wx.removeStorageSync('showHomeDialog')
  wx.removeStorageSync('biddingData')
  wx.removeStorageSync('buyShopData')
  wx.removeStorageSync('recruitData')
  wx.removeStorageSync('sellShopData')
  wx.removeStorageSync('supplyData')
  wx.removeStorageSync('resumeData')
  wx.removeStorageSync('otherId')
  wx.removeStorageSync('otherShareTime')
}

export { HTTP }
